<html xmlns:th="http://www.thymeleaf.org">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link rel="stylesheet" href="./static/jexcel/dist/jsuites.css" type="text/css" />
<link rel="stylesheet" href="./static/jexcel/dist/jexcel.css" type="text/css" />
<link rel="stylesheet" href="./static/jexcel/dist/layer-animate.css" type="text/css" />
<link rel="stylesheet" href="./static/jexcel/dist/icon.css" type="text/css"/>
<div id="spreadsheet"></div>
<input type="hidden" id="id" th:value=${id}>
<script src="./static/jexcel/dist/jquery.min.js"></script>
<script src="./static/jexcel/dist/method.js"></script>
<script src="./static/jexcel/dist/jexcel.js"></script>
<script src="./static/jexcel/dist/jsuites.js"></script>
<script>

var datas = [];//表格基础数据
var table;//api生成的表格对象
var rules;//模板的所有验证规则对象
var cells;//模板的所有单元格对象


//工具栏
var toolbar=[
{
    type: 'i',
    title:'保存',
    content: 'save',//保存按钮
    onclick: function () {
    	var cftName,cftCode,temType;//模板名称，模板编码，模板类型（检验、问题反馈、安全审批）
    	//去掉选中的单元格的高亮样式
    	$(".highlight-selected").each(function(){
    		$(this).removeClass("highlight-selected");
    		$(this).removeClass("highlight");
    		$(this).removeClass("highlight-top");
    		$(this).removeClass("highlight-bottom");
    		$(this).removeClass("highlight-left");
    		$(this).removeClass("highlight-right");
    	});
		//新增
    	if($("#id").val()=="0"){
    		var dialog={
    				//弹出新增模板的对话框，需要输入模板名称、编码和类型
                    type:"showSweetAlert",
                    title:"新增表单模板",
                    content:"<div><span>模板名称：</span><input type='text' id='name'></div>"+
                    "<div style='margin-top:10px'><span>模板编码：</span><input type='text' id='code'></div>",
                    btn:["","确定"],
                    callBack2: function () {
                    	//确定按钮点击事件
                    	cftName=$("#name").val();
                    	cftCode=$("#code").val();
                    	if(cftName==""||cftCode==""){
                    		alert("请输入模板名称和编码");
                    	}
                    	else{
                    		//判断模板名称和编码是否可用
                    		if(true){
								var url="./add";//后台调用路径
								if(url!=""){
									get();//获取当前模板中所有的数据
                        			var i,cell,rule,time,select,checkbox;
                        	    	//模板有单元格时，将单元格的各种属性赋值到cell中，用以提交
                        			if(cells.length!=0){
                        	    		var array=[];
                        	    		for(i=0;i<cells.length;i++){ 
                        	        	    array.push({"cellName":cells[i][0],"datax":cells[i][1],"datay":cells[i][2],"classes":cells[i][3],"style":cells[i][4],"colspan":cells[i][5],"rowspan":cells[i][6],"datamerged":cells[i][7],"innerHTML":cells[i][8],"clientWidth":cells[i][9],"clientHeight":cells[i][10],"formula":cells[i][11]}); 
                        	        	}
                        	    		cell=JSON.stringify(array);
                        	    	}
                        	    	//模板有校验规则时，将规则赋值到rule中，用以提交
                        	    	if(rules.length!=0){
                        	    		var array=[];
                        	    		for(i=0;i<rules.length;i++){ 
                        	        	    array.push({"cellName":rules[i][0],"min":rules[i][1],"normal":rules[i][2],"max":rules[i][3]}); 
                        	        	}
                        	    		rule=JSON.stringify(array);
                        	    	}
                        	    	//模板有时间格式的单元格时，赋值到time中，用以提交
                        	    	if(table.times.length!=0){
                        	    		var array=[];
                        	    		for(i=0;i<table.times.length;i++){ 
                        	        	    array.push({"cellName":table.times[i][0],"time":table.times[i][1],"type":table.times[i][2]}); 
                        	        	}
                        	    		time=JSON.stringify(array);
                        	    	}
                        	    	//模板有下拉框格式的单元格时，赋值，用以提交
                        	    	if(table.selects.length!=0){
                        	    		var array=[];
                        	    		for(i=0;i<table.selects.length;i++){ 
                        	        	    array.push({"cellName":table.selects[i][0],"value":table.selects[i][1],"datas":table.selects[i][2],"type":table.selects[i][3],"code":table.selects[i][4]}); 
                        	        	}
                        	    		select=JSON.stringify(array);
                        	    	}
                        	    	//模板有复选框格式的单元格时，赋值，用以提交
                        	    	if(table.checkboxs.length!=0){
                        	    		var array=[];
                        	    		for(i=0;i<table.checkboxs.length;i++){ 
                        	        	    array.push({"cellName":table.checkboxs[i][0],"value":table.checkboxs[i][1]}); 
                        	        	}
                        	    		checkbox=JSON.stringify(array);
                        	    	}
                        	    	//将模板中的所有数据提交到后台
                        	        $.post(url,{"name":cftName,"code":cftCode,"cells":cell,"rules":rule,"times":time,"selects":select,"checkboxs":checkbox},function(data){
                        	        	if(data.success){
                        	        		alert("新增成功");
                        	        		method.msg_close();
                        	        	}
                        	        	else{
                        	        		alert("新增失败");
                        	        	}
                        	        },"json");
								}
								else{
									alert("先完善后台代码再保存！");
								}
							}
							else{
								alert("模板名称或编码重复！");
							}
                    	}
                	}
        	};
        	method.msg_layer(dialog);
    	}
    	//更新保存
    	else{
    		get();//获取模板的所有数据
			var i,cell,rule,time,select,checkbox;
	    	if(cells.length!=0){
	    		var array=[];
	    		for(i=0;i<cells.length;i++){ 
	        	    array.push({"cellName":cells[i][0],"datax":cells[i][1],"datay":cells[i][2],"classes":cells[i][3],"style":cells[i][4],"colspan":cells[i][5],"rowspan":cells[i][6],"datamerged":cells[i][7],"innerHTML":cells[i][8],"clientWidth":cells[i][9],"clientHeight":cells[i][10],"formula":cells[i][11]}); 
	        	}
	    		cell=JSON.stringify(array);
	    	}
	    	if(rules.length!=0){
	    		var array=[];
	    		for(i=0;i<rules.length;i++){ 
	        	    array.push({"cellName":rules[i][0],"min":rules[i][1],"normal":rules[i][2],"max":rules[i][3]}); 
	        	}
	    		rule=JSON.stringify(array);
	    	}
	    	if(table.times.length!=0){
	    		var array=[];
	    		for(i=0;i<table.times.length;i++){ 
	        	    array.push({"cellName":table.times[i][0],"time":table.times[i][1],"type":table.times[i][2]}); 
	        	}
	    		time=JSON.stringify(array);
	    	}
	    	if(table.selects.length!=0){
	    		var array=[];
	    		for(i=0;i<table.selects.length;i++){ 
	        	    array.push({"cellName":table.selects[i][0],"value":table.selects[i][1],"datas":table.selects[i][2],"type":table.selects[i][3],"code":table.selects[i][4]}); 
	        	}
	    		select=JSON.stringify(array);
	    	}
	    	if(table.checkboxs.length!=0){
	    		var array=[];
	    		for(i=0;i<table.checkboxs.length;i++){ 
	        	    array.push({"cellName":table.checkboxs[i][0],"value":table.checkboxs[i][1]}); 
	        	}
	    		checkbox=JSON.stringify(array);
	    	}
	    	var url="./update";
			var id=$("#id").val();
			if(url!=""){
				$.post(url,{"id":id,"cells":cell,"rules":rule,"times":time,"selects":select,"checkboxs":checkbox},function(data){
		        	if(data.success){
		        		alert("保存成功");
		        	}
		        	else{
		        		alert("保存失败");
		        	}
		        },"json");
			}
			else{
				alert("请先完善后台代码再保存！");
			}
    	}
    	
    }
},
{
    type: 'i',
    content: 'print',
    title:'打印',
    onclick: function() {
    	$(".highlight-selected").each(function(){
    		$(this).removeClass("highlight-selected");
    		$(this).removeClass("highlight");
    		$(this).removeClass("highlight-top");
    		$(this).removeClass("highlight-bottom");
    		$(this).removeClass("highlight-left");
    		$(this).removeClass("highlight-right");
    	});
    	get();
    	if(table.times.length!=0){
    		var array=[];
    		for(i=0;i<table.times.length;i++){ 
    			table.setValue(table.times[i][0],table.times[i][1]);
        	}
    	}
    	if(table.selects.length!=0){
    		var array=[];
    		for(i=0;i<table.selects.length;i++){
    			table.setValue(table.selects[i][0],table.selects[i][1]);
        	}
    	}
    	if(table.checkboxs.length!=0){
    		var array=[];
    		for(i=0;i<table.checkboxs.length;i++){ 
    			var input;
    			var cell = jexcel.getIdFromColumnName(table.checkboxs[i][0], true);
                var x = cell[0];
                var y = cell[1];
                var td=table.tbody.children[y].children[x+1];
    			if(table.checkboxs[i][1]==true||table.checkboxs[i][1]=='true'){
    				input="<input type='checkbox' checked='checked'>";
    			}
    			else{
    				input="<input type='checkbox'>";
    			}
    			td.innerHTML=input;
        	}
    	}
    	$("colgroup").children(':first').remove();//删除第一列列宽
    	$("thead[class='resizable']").children(':first').remove();//删除表头ABCD...
    	$("tbody[class='resizable']").find('.jexcel_row').remove();//删除行头1234...
    	var html=$(".jexcel_content").html();
		document.getElementsByTagName('body')[0].innerHTML = html;
	    setTimeout(function () {
	    	window.print();
	    	//window.location.reload(true);
	    }, 1000);
    	
    }
},{
	type: 'i',
	title:'撤销',
    content: 'undo',//撤销按钮
    onclick: function() {
        table.undo();
    }
},
{
    type: 'i',
    title:'恢复',
    content: 'redo',//取消撤销按钮
    onclick: function() {
        table.redo();
    }
},
{
	type: 'i',
	title:'上传图片',
    content: 'image',//上传图片按钮
    onclick: function () {
    	var rows=table.getSelectedRows().length;
    	var cols=table.getSelectedColumns().length;
    	var td=table.tbody.children[parseInt(table.getSelectedRows()[0].getAttribute("data-y"))].children[table.getSelectedColumns()[0]+1];
    	var path="";
    	var dialog={//弹出图片上传对话框
                type:"showSweetAlert",
                title:"上传图片",
                content:"<div><input type='file' id='image' name='image'></div>",
                btn:["","上传"],
                callBack2: function () {
                	
                	path=$("#image").val();
                	if(path==""){
                		alert('请选择图片上传');
                	}
                	else{
                		var form = new FormData();
                		form.append("file", document.getElementById("image").files[0]);
                		$.ajax({
                			//上传图片
                            url: "upload",        //后台url
                            data: form,
                            cache: false,
                            async: false,
                            type: "POST",                   //类型，POST或者GET
                            dataType: 'json',              //数据返回类型，可以是xml、json等
                            processData: false,
                            contentType: false,
                            success: function (data) {      //成功，回调函数
                                if (data.success) {
                                	//将单元格的值设置为图片
                                	var img = document.createElement('img');
                                    img.src = data.path;
                                    img.title=data.path;
                                    td.innerHTML="";
                                    td.appendChild(img);
                            		method.msg_close();
                                	
                                } else {
                                	alert("图片上传失败");
                                }
                                
                            },
                            error: function (er) {          //失败，回调函数
                            	alert("图片上传失败");
                                console.log(er)
                            }
                        });	
                	}
            	}
    	};
    	method.msg_layer(dialog);
    }
},
{
    type: 'i',
    title:'上传文件',
    content: 'folder',//上传文件
    onclick: function () {
    	var rows=table.getSelectedRows().length;
    	var cols=table.getSelectedColumns().length;
    	var td=table.tbody.children[parseInt(table.getSelectedRows()[0].getAttribute("data-y"))].children[table.getSelectedColumns()[0]+1];
    	var path="";
    	var dialog={
                type:"showSweetAlert",
                title:"上传文件",
                content:"<div><input type='file' id='file' name='file'></div>",
                btn:["","上传"],
                callBack2: function () {
                	path=$("#file").val();
                	if(path==""){
                		alert('请选择文件上传');
                	}
                	else{
                		var form = new FormData();
                		form.append("file", document.getElementById("file").files[0]);
                		$.ajax({
                            url: "upload",        //后台url
                            data: form,
                            cache: false,
                            async: false,
                            type: "POST",                   //类型，POST或者GET
                            dataType: 'json',              //数据返回类型，可以是xml、json等
                            processData: false,
                            contentType: false,
                            success: function (data) {      //成功，回调函数
                                if (data.success) {
                                	//将单元格的值设置为超链接
                                	var a = document.createElement('a');
			                		a.href=data.path;
			                        a.target='_blank';
			                		a.innerHTML="下载文件"
			                        td.innerHTML="";
			                        td.appendChild(a);
			                		method.msg_close();

                                } else {
                                	alert("文件上传失败");
                                }
                            },
                            error: function (er) {          //失败，回调函数
                            	alert("文件上传失败");
                            }
                        });	
                	}
            	}
    	};
    	method.msg_layer(dialog);
    }
},
{
    type: 'i',
    title:'设置复选框',
    content: 'check_box',//设置复选框
    onclick: function () {
    	var rows=table.getSelectedRows().length;
    	var selectRows=table.getSelectedRows();
    	var cols=table.getSelectedColumns().length;
    	var selectCols=table.getSelectedColumns();
    	var i,j;
    	//遍历选择的所有单元格
    	for(i=0;i<rows;i++){
    		for(j=0;j<cols;j++){
    			var td=table.tbody.children[parseInt(selectRows[i].getAttribute("data-y"))].children[selectCols[j]+1];
    			if(td.dataset.merged=="true"){
					rows=1;
					cols=1;
				}
    			var cellName = jexcel.getColumnNameFromId([selectCols[j],parseInt(selectRows[i].getAttribute("data-y"))]);
    			//设置单元格内容为checkbox
    			var input = document.createElement('input');
    			input.type='checkbox';
    			input.id='checkbox'+cellName;
    			td.classList.add('checkbox');
                td.innerHTML="";
                td.appendChild(input);
    		}
    	}
    }
},
{
    type: 'i',
    title:'年-月-日',
    content: 'date_range',//设置日期
    onclick: function () {
    	var rows=table.getSelectedRows().length;
    	var selectRows=table.getSelectedRows();
    	var cols=table.getSelectedColumns().length;
    	var selectCols=table.getSelectedColumns();
    	var i,j;
    	//遍历所选单元格
    	for(i=0;i<rows;i++){
    		for(j=0;j<cols;j++){
    			var td=table.tbody.children[parseInt(selectRows[i].getAttribute("data-y"))].children[selectCols[j]+1];
    			if(td.dataset.merged=="true"){
					rows=1;
					cols=1;
				}
				var cellName = jexcel.getColumnNameFromId([selectCols[j],parseInt(selectRows[i].getAttribute("data-y"))]);
    			var cell=td;
    			var format='YYYY/MM/DD';
    			var value=table.getValue(cellName);
    			var formatted = jSuites.calendar.extractDateFromString(value, format);
                table.setValue(cellName,"");
                var info = cell.getBoundingClientRect();
                var editor = document.createElement('input');
                editor.style.width = (info.width) + 'px';
                //editor.style.height = (info.height - 2) + 'px';
                //editor.style.minHeight = (info.height - 2) + 'px';
                editor.style.minWidth = '95px';
                editor.style.maxWidth = '95px';
                //把单元格内容设置为时间格式
                cell.classList.add('editor');
                cell.innerHTML = '';
                cell.appendChild(editor);
                //时间选择器关闭监听事件
                table.options.columns[j].options.onclose = function(el, value) {
                	//监听时间的改变
                	var selectRows=table.getSelectedRows();
					var selectCols=table.getSelectedColumns();
					td=table.tbody.children[parseInt(selectRows[0].getAttribute("data-y"))].children[selectCols[0]+1];
            		cellName = jexcel.getColumnNameFromId([selectCols[0],parseInt(selectRows[0].getAttribute("data-y"))]);
                	cell=td;
            		//监听时间的改变
                	var time=cell.children[0].calendar.close(true);//当前选择的时间
                	var a;
                	for(a=0;a<table.times.length;a++){
                		if(table.times[a][0]==cellName){
                			table.times[a][1]=time.substring(0,10);
                			break;
                		}
                	}
                	
                }
                //设置时间格式单元格的格式
                table.options.columns[j].options.format='YYYY/MM/DD';
                table.options.columns[j].options.time='1';
                var myDate = new Date();
                var year = myDate.getFullYear();
                var month = myDate.getMonth() + 1;
                var date = myDate.getDate();

                //月份的显示为两位数字如09月
                if(month < 10 ){
                month = "0" + month;
                }
                if(date < 10 ){
                date = "0" + date;
                }
                
                var dateTime = year + "-" + month + "-" + date ;
                //设置初始值为当前时间
                table.options.columns[j].options.value=dateTime;
              	//单元格内容初始化时，如果该单元格已有时间，则把原有时间替换为time，若没有，则新增
                if(table.times.length==0){
            		var t=[];
                	t[0]=cellName;
                	t[1]=dateTime;
                	t[2]='date';
                	table.times[0]=t;
            	}
            	else{
            		for(a=0;a<table.times.length;a++){
                		if(table.times[a][0]==cellName){
                			table.times[a][1]=dateTime;
                			table.times[a][2]='date';
                			break;
                		}
                		if(a==table.times.length-1){
                			var t=[];
                        	t[0]=cellName;
                        	t[1]=dateTime;
                        	t[2]='date';
                        	table.times[a+1]=t;
                		}
                	}
            	}
              	//渲染时间格式的单元格
                jSuites.calendar(editor,table.options.columns[j].options);
                editor.focus(); 
    		}
    	}
    }
},
{
    type: 'i',
    title:'年-月-日 时:分',
    content: 'access_time',//设置日期+时间格式
    onclick: function () {
    	var rows=table.getSelectedRows().length;
    	var selectRows=table.getSelectedRows();
    	var cols=table.getSelectedColumns().length;
    	var selectCols=table.getSelectedColumns();
    	var i,j;
    	//遍历所选单元格
    	for(i=0;i<rows;i++){
    		for(j=0;j<cols;j++){
    			var td=table.tbody.children[parseInt(selectRows[i].getAttribute("data-y"))].children[selectCols[j]+1];
    			if(td.dataset.merged=="true"){
					rows=1;
					cols=1;
				}
				var cellName = jexcel.getColumnNameFromId([selectCols[j],parseInt(selectRows[i].getAttribute("data-y"))]);
    			var cell=td;
    			var format='YYYY/MM/DD HH24:MI:SS';
    			var value=table.getValue(cellName);
    			var formatted = jSuites.calendar.extractDateFromString(value, format);
                table.setValue(cellName,"");
                var info = cell.getBoundingClientRect();
                var editor = document.createElement('input');
                editor.style.width = (info.width) + 'px';
                //editor.style.height = (info.height - 2) + 'px';
                //editor.style.minHeight = (info.height - 2) + 'px';
                editor.style.minWidth = '150px';
                editor.style.maxWidth = '150px';
                //把单元格内容设置为时间格式
                cell.classList.add('editor');
                cell.innerHTML = '';
                cell.appendChild(editor);
                //时间选择器关闭监听事件
                table.options.columns[j].options.onclose = function(el, value) {
                	//监听时间的改变
                	var selectRows=table.getSelectedRows();
					var selectCols=table.getSelectedColumns();
					td=table.tbody.children[parseInt(selectRows[0].getAttribute("data-y"))].children[selectCols[0]+1];
            		cellName = jexcel.getColumnNameFromId([selectCols[0],parseInt(selectRows[0].getAttribute("data-y"))]);
                	cell=td;
            		//监听时间的改变
                	var time=cell.children[0].calendar.close(true);//当前选择的时间
                	var a;
                	for(a=0;a<table.times.length;a++){
                		if(table.times[a][0]==cellName){
                			table.times[a][1]=time;
                			break;
                		}
                	}
                	
                }
                //设置时间格式单元格的格式
                table.options.columns[j].options.format='YYYY/MM/DD HH24:MI:SS';
                table.options.columns[j].options.time='1';
                var myDate = new Date();
                var year = myDate.getFullYear();
                var month = myDate.getMonth() + 1;
                var date = myDate.getDate();
                var hours = myDate.getHours();
                var minutes = myDate.getMinutes();
                var seconds = myDate.getSeconds();

                //月份的显示为两位数字如09月
                if(month < 10 ){
                month = "0" + month;
                }
                if(date < 10 ){
                date = "0" + date;
                }
                if(hours < 10 ){
                	hours = "0" + hours;
                }
                if(minutes < 10 ){
                	minutes = "0" + minutes;
                }
                if(seconds < 10 ){
                	seconds = "0" + seconds;
                }
                var dateTime = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
                //设置初始值为当前时间
                table.options.columns[j].options.value=dateTime;
              	//单元格内容初始化时，如果该单元格已有时间，则把原有时间替换为time，若没有，则新增
                if(table.times.length==0){
            		var t=[];
                	t[0]=cellName;
                	t[1]=dateTime;
                	t[2]='datetime';
                	table.times[0]=t;
            	}
            	else{
            		for(a=0;a<table.times.length;a++){
                		if(table.times[a][0]==cellName){
                			table.times[a][1]=dateTime;
                			table.times[a][2]='datetime';
                			break;
                		}
                		if(a==table.times.length-1){
                			var t=[];
                        	t[0]=cellName;
                        	t[1]=dateTime;
                        	t[2]='datetime';
                        	table.times[a+1]=t;
                		}
                	}
            	}
              	//渲染时间格式的单元格
                jSuites.calendar(editor,table.options.columns[j].options);
                editor.focus(); 
    		}
    	}
    }
},

{
	type:'i',
	title:'设置下拉框',
	content:'arrow_drop_down_circle',//设置下拉框格式
	onclick:function(){
		var rows=table.getSelectedRows().length;
    	var selectRows=table.getSelectedRows();
    	var cols=table.getSelectedColumns().length;
    	var selectCols=table.getSelectedColumns();
    	var i,j,datas;
    	var dialog={//弹出对话框，选择要设置的下拉框的内容
                type:"showSweetAlert",
                title:"设置下拉选项",
                content:"<div><span>数据类型：</span><select id='type' style='line-height:25px'>"+
                "<option value='1'>以半角';'分隔的数据</option>"+
                "</select></div>"+
                "<div style='margin-top:20px'><textarea rows='8' placeholder='数据值' cols='34' id='datas'></textarea></div>",
                btn:["","确定"],
                callBack1: function () {
                	
            	},
                callBack2: function () {
                	//所选类型值不为3时，都需要输入数据值
                	if($("#datas").val()==""&&$("#type").val()!="3"){
                		alert("请输入数据值");
                	}
                	else{
                		var type=$("#type").val();
                		var dict_code="";
                		//选择不同的类型，赋与datas不同的值
                		if(type=="1"||type=="7"){
                			datas=$("#datas").val();
                			if(datas.indexOf('；')!=-1){
                				alert("请输入半角的分号");
                				return;
                			}
                		}
                		for(i=0;i<rows;i++){
                    		for(j=0;j<cols;j++){
                    			var td=table.tbody.children[parseInt(selectRows[i].getAttribute("data-y"))].children[selectCols[j]+1];
								if(td.dataset.merged=="true"){
									rows=1;
									cols=1;
								}
                    			var cellName = jexcel.getColumnNameFromId([selectCols[j],parseInt(selectRows[i].getAttribute("data-y"))]);
                    			var cell=td;
                    			var key=table.getValue(cellName);
                    			//给单元格设置下拉框格式的class
                    			td.classList.add('jexcel_dropdown');
                    			var v = [];
                    			var combo = [];
                                var source = datas.split(";");
                    
                                for (var k = 0; k < source.length; k++) {
                                    if (typeof(source[k]) == 'object') {
                                        combo[source[k].id] = source[k].name;
                                    } else {
                                        combo[source[k]] = source[k];
                                    }
                                }
                    			var keys = ('' + key).split(';');
                                for (var k = 0; k < keys.length; k++) {
                                    if (combo[keys[k]]) {
                                        v.push(combo[keys[k]]);
                                    }
                                }
                                cell.innerHTML=(v.length > 0) ? v.join('; ') : '';
                                var value = key;
                                var data = [];
                                //data是最终初始化下拉框选项的数组
                                for (var k = 0; k < source.length; k++) {
                                    data.push(source[k]);
                                }
                                var info = cell.getBoundingClientRect();
                                var editor = document.createElement('div');
                                editor.style.width = (info.width) + 'px';
                                //editor.style.height = (info.height - 2) + 'px';
                                //editor.style.minHeight = (info.height - 2) + 'px';
                                cell.classList.add('editor');
                                cell.innerHTML = '';
                              	//添加一个下拉框
                                cell.appendChild(editor);
                                //table.selects是最开始声明的全局变量，用来存放所有的下拉框内容
                                //判断当前单元格是否有下拉框，没有则新增第一个
                                if(table.selects.length==0){
                            		var t=[];
                                	t[0]=cellName;//单元格:A5
                                	t[1]='';//所选值:3
                                	t[2]=datas;//选项值:1;2;3;4
                                	t[3]=type;//下拉框类型:1
                                	t[4]=dict_code;//代码值:$(#datas).val()
                                	table.selects[0]=t;
                            	}
                                //当前单元格存在下拉框
                            	else{
                            		var a;
                            		for(a=0;a<table.selects.length;a++){
                                		//如果点击的是一个下拉框单元格，则更新他的select
                            			if(table.selects[a][0]==cellName){
                                			table.selects[a][1]='';
                                			table.selects[a][2]=datas;
                                			table.selects[a][3]=type;
                                			table.selects[a][4]=dict_code;
                                			break;
                                		}
                                		//否则，新增一个select
                                		if(a==table.selects.length-1){
                                			var t=[];
                                        	t[0]=cellName;
                                        	t[1]='';
                                        	t[2]=datas;
                                        	t[3]=type;
                                        	t[4]=dict_code;
                                        	table.selects[a+1]=t;
                                		}
                                	}
                            	}
                                var wrap=false;
                                var options = {
                                    data: data,
                                    wrap:wrap,
                                    multiple: false,
                                    autocomplete: false,
                                    opened:false,
                                    value: value,
                                    width:'100%',
                                    height:editor.style.minHeight,
                                    position: false,
                                    //下拉框展开时监听事件
                                    onopen:function(){
                                    	//展开时重新赋值下拉框的各种属性
                                    	var selectRows=table.getSelectedRows();
    	    							var selectCols=table.getSelectedColumns();
    	    							td=table.tbody.children[parseInt(selectRows[0].getAttribute("data-y"))].children[selectCols[0]+1];
    	                    			cellName = jexcel.getColumnNameFromId([selectCols[0],parseInt(selectRows[0].getAttribute("data-y"))]);
    			                		cell=td;
    			                		var a;
                                    	for(a=0;a<table.selects.length;a++){
                                        	if(table.selects[a][0]==cellName){
                                        		type=table.selects[a][3];
                                        		dict_code=table.selects[a][4];
                                        		break;
                                        	}
                                    	}
                                    },
                                    //下拉框关闭监听事件
                                    onclose:function() {
                                    	if(cell.children.length>0){
                                    		var dropdownValue=cell.children[0].dropdown.close(true);
                                        	var a;
                                        	for(a=0;a<table.selects.length;a++){
                                        		if(table.selects[a][0]==cellName){
                                        			table.selects[a][1]=dropdownValue;//将关闭时选中的值赋给selects
                                        			break;
                                        		}
                                        	}
                                    	}
                                    }
                                };
                                //渲染下拉框
                                jSuites.dropdown(editor, options);
                    		}
                    	}
                		method.msg_close();
                	}
            	}
    	};
    	method.msg_layer(dialog);
	},
},
{
    type: 'select',
    k: 'font-family',//字体选项
    v: ['Arial','Verdana','宋体','黑体','楷体']
},
{
    type: 'select',
    k: 'font-size',//字体大小选项
    v: ['8px','10px','12px','14px','16px','18px','20px','22px','24px','26px','28px','30px']
},
{
	type: 'i',
	title:'无边框',
    content: 'border_clear',//单元格边框
    k: 'border-style',
    v: 'none none none none'
},
{
	type: 'i',
	title:'上边框',
    content: 'border_top',//单元格边框
    k: 'border-style',
    v: 'solid none none none'
},
{
	type: 'i',
	title:'上左边框',
    content: 'border_style',//单元格边框
    k: 'border-style',
    v: 'solid none none solid'
},
{
	type: 'i',
	title:'左边框',
    content: 'border_left',//单元格边框
    k: 'border-style',
    v: 'none none none solid'
},
{
    type: 'i',
    title:'居左',
    content: 'format_align_left',//居左
    k: 'text-align',
    v: 'left'
},
{
    type:'i',
    title:'居中',
    content:'format_align_center',//居中
    k:'text-align',
    v:'center'
},
{
    type: 'i',
    title:'居右',
    content: 'format_align_right', //居右
    k: 'text-align',
    v: 'right'
},
{
    type: 'i',
    title:'加粗',
    content: 'format_bold',//加粗
    k: 'font-weight',
    v: 'bold'
},
{
    type: 'color',
    title:'字体颜色',
    content: 'format_color_text',//字体颜色
    k: 'color'
},
/* {
    type: 'color',
    content: 'format_color_fill',//单元格背景色
    k: 'background-color'
}, */
{
    type: 'i',
    title:'清除格式和数据',
    content: 'delete',//清空格式和删除数据
    onclick: function() {
    	var rows=table.getSelectedRows().length;
    	var selectRows=table.getSelectedRows();
    	var cols=table.getSelectedColumns().length;
    	var selectCols=table.getSelectedColumns();
    	var i,j;
    	for(i=0;i<rows;i++){
    		for(j=0;j<cols;j++){
    			var td=table.tbody.children[parseInt(selectRows[i].getAttribute("data-y"))].children[selectCols[j]+1];
    			//清楚格式的时候先判断一下是不是日期和下拉框，如果是，
    			//再删除数据格式的时候，同时删除全局变量里的值times和selects
    			if(td.getAttribute("class").indexOf('editor')!=-1&&td.innerHTML.indexOf('data-mask')!=-1){
    				//删除times对应的单元格时间数据
    				var cellName = jexcel.getColumnNameFromId([selectCols[j],parseInt(selectRows[i].getAttribute("data-y"))]);
    				var a;
                	for(a=0;a<table.times.length;a++){
                		if(table.times[a][0]==cellName){
                			table.times.splice(a,1)
                			break;
                		}
                	}
    			}
    			if(td.getAttribute("class").indexOf('jexcel_dropdown')!=-1){
    				//删除selects对应的单元格下拉数据
    				var cellName = jexcel.getColumnNameFromId([selectCols[j],parseInt(selectRows[i].getAttribute("data-y"))]);
    				var a;
                	for(a=0;a<table.selects.length;a++){
                		if(table.selects[a][0]==cellName){
                			table.selects.splice(a,1)
                			break;
                		}
                	}
    			}
    			td.setAttribute('class','');
    			td.innerHTML='';
    			table.options.data[parseInt(selectRows[i].getAttribute("data-y"))][selectCols[j]]='';
    		}
    	}
    }
}];

var editable=true;//可编辑
var wordWrap=true;//单元格可换行
var columnResize=true;//可调整列宽
var rowResize=true;//可调整行高
var template="";
var detail=""
var rows=10;//行数
var cols=12;//列数
var r=new Array();
var c=new Array();
//初始化表格X*Y
for(var i=0;i<rows;i++){
	var d=[];
	for(var j=0;j<cols;j++){
		d.push('');
	}
	datas.push(d);
}
var id=$("#id").val();
	if(id=="0"){
		
		//初始化列宽
		var xx=0;
		for(var i=0;i<cols;i++){
			var obj1=new Object();
			obj1.width=80;
			c.push(obj1);
		}
		//初始化行高
		var yy=0;
		for(var i=0;i<rows;i++){
			var obj2=new Object();
			obj2.height=40;
			r.push(obj2);
		}
		//初始化表格
		table= jexcel(document.getElementById('spreadsheet'), {
			data:datas,
			toolbar:toolbar,
			columns:c,
			rows:r,
			editable:editable,
			wordWrap:wordWrap,
			columnResize:columnResize,
			rowResize:rowResize
		});
		cells=[];
		table.times=[];//二维数组用于存放所有时间数据
		table.checkboxs=[];//二维数组用于存放所有checkbox数据
		table.selects=[];//二维数组用于存放所有下拉框数据
	}
	else{
		$.get("./getDetail",{"id":id},function(data){
			template=data.template;//模板的基本数据
			detail=data.detail;//所有单元格的数据
			rows=data.rows;//行数
			cols=data.cols;//列数
			//初始化行高
			var yy=0;
			for(var i=0;i<detail.length;i++){
				var y=parseInt(detail[i].datay);
				if(yy==y){
					var obj1={};
					obj1.height=parseInt(detail[i].clientheight)
					r.push(obj1);
					if(yy<rows-1){
						yy++;
						i=-1;
					}
					else{
						break;
					}
				}
			}
			//初始化列宽
			var xx=0;
			for(var i=0;i<detail.length;i++){
				var x=parseInt(detail[i].datax);
				if(xx==x){
					var obj={};
					obj.width=parseInt(detail[i].clientwidth);
					c.push(obj);
					if(xx<cols-1){
						xx++;
						i=-1;
					}
					else{
						break;
					}
				}
			}
			//初始化表格
			table= jexcel(document.getElementById('spreadsheet'), {
				data:datas,
				toolbar:toolbar,
				columns:c,
				rows:r,
				editable:editable,
				wordWrap:wordWrap,
				columnResize:columnResize,
				rowResize:rowResize
			});
			cells=[];
			table.times=[];//二维数组用于存放所有时间数据
			table.checkboxs=[];//二维数组用于存放所有checkbox数据
			table.selects=[];//二维数组用于存放所有下拉框数据
			
			//初始化单元格的公式
			for(var i=0;i<detail.length;i++){
				var y=parseInt(detail[i].datay);
				var x=parseInt(detail[i].datax)+1
				if(null!=detail[i].formula){
					table.options.data[y][x-1]=detail[i].formula;
				}
				else{
					table.options.data[y][x-1]='';
				}
			}
			table.refresh(); 
			//初始化表格显示的数据
			for(var i=0;i<detail.length;i++){
				var y=parseInt(detail[i].datay);
				var x=parseInt(detail[i].datax)+1
				var td=table.tbody.children[y].children[x];
				var cellName=detail[i].cellname;
				
				if(null!=detail[i].innerhtml){
					td.innerHTML=detail[i].innerhtml;
				}
				else{
					td.innerHTML='';
				}
				if(null!=detail[i].classes){
					td.setAttribute('class',detail[i].classes);
					//复选框
					if(detail[i].classes.indexOf('checkbox')!=-1){
						var jo= jQuery.parseJSON(template.checkboxs);
						if(jo==null||jo=="null"){
							jo=[];
						}
						for(var q=0;q<jo.length;q++){
							if(cellName==jo[q].cellName){
								//var inner=td.innerHTML.substring(0,td.innerHTML.length-1);
								
								if(jo[q].value=='true'){
									if(editable){
										td.innerHTML='<input type="checkbox" id="checkbox'+cellName+'" checked="checked">';
									}
									else{
										td.innerHTML='<input type="checkbox" id="checkbox'+cellName+'" checked="checked" disabled="disabled">';
									}
								}
								else{
									if(editable){
										td.innerHTML='<input type="checkbox" id="checkbox'+cellName+'">';
									}
									else{
										td.innerHTML='<input type="checkbox" id="checkbox'+cellName+'" disabled="disabled">';
									}
								}
							}
							
						}
					}
					//日期时间
					else if(detail[i].classes.indexOf('editor')!=-1&&detail[i].innerhtml.indexOf('data-mask')!=-1){
						
						var jo= jQuery.parseJSON(template.times);
						if(jo==null||jo=="null"){
							jo=[];
						}
						for(var q=0;q<jo.length;q++){
							if(cellName==jo[q].cellName){
								//var time=jo[q].time;
								var format='YYYY/MM/DD HH24:MI:SS';
								var dateType="datetime";
								if(jo[q].type=='date'){
									format='YYYY/MM/DD';
									dateType="date";
								}
				    			var value=jo[q].time;
				    			var cell=td;
				    			cell.classList.add('editor');
				    			if(editable){
				    				var formatted = jSuites.calendar.extractDateFromString(value, format);
					                table.setValue(cellName,"");
					                var info = cell.getBoundingClientRect();
					                var editor = document.createElement('input');
					                editor.style.width = (info.width) + 'px';
					                //editor.style.height = (info.height - 2) + 'px';
					                //editor.style.minHeight = (info.height - 2) + 'px';
					                var width='150px';
					                if(jo[q].type=='date'){
					                	width='95px';
									}
					                editor.style.minWidth = width;
					                editor.style.maxWidth = width;
					                
					                cell.innerHTML = '';
					                cell.appendChild(editor);
					                
					                table.options.columns[x-1].options.onclose = function(el, value) {
					                	var selectRows=table.getSelectedRows();
			    						var selectCols=table.getSelectedColumns();
			    						td=table.tbody.children[parseInt(selectRows[0].getAttribute("data-y"))].children[selectCols[0]+1];
			                    		cellName = jexcel.getColumnNameFromId([selectCols[0],parseInt(selectRows[0].getAttribute("data-y"))]);
					                	cell=td;
			                    		//监听时间的改变
					                	var time=cell.children[0].calendar.close(true);//当前选择的时间
					                	var a;
					                	for(a=0;a<table.times.length;a++){
				                    		if(table.times[a][0]==cellName){
				                    			if(table.times[a][2]=="date"){
				                    				time=time.substring(0,10);
				                    			}
				                    			table.times[a][1]=time;
				                    			break;
				                    		}
					                	}
					                }
					                table.options.columns[x-1].options.format=format;
					                table.options.columns[x-1].options.time='1';
					                table.options.columns[x-1].options.value=value;
					                if(table.times.length==0){
				                		var t=[];
				                    	t[0]=cellName;
				                    	t[1]=value;
				                    	t[2]=dateType;
				                    	table.times[0]=t;
				                	}
				                	else{
				                		for(a=0;a<table.times.length;a++){
				                    		if(table.times[a][0]==cellName){
				                    			table.times[a][1]=value;
				                    			table.times[a][2]=dateType;
				                    			break;
				                    		}
				                    		if(a==table.times.length-1){
				                    			var t=[];
				                            	t[0]=cellName;
				                            	t[1]=value;
				                            	t[2]=dateType;
				                            	table.times[a+1]=t;
				                    		}
				                    	}
				                	}
					                jSuites.calendar(editor,table.options.columns[x-1].options);
					                editor.focus();
				    			}
				    			else{
				    				table.setValue(cellName,value);
				    			}
				    			
							}
						}
					}
					//下拉框
					else if(detail[i].classes.indexOf('jexcel_dropdown')!=-1){
						var jo= jQuery.parseJSON(template.selects);
						if(jo==null||jo=="null"){
							jo=[];
						}
						for(var q=0;q<jo.length;q++){
							if(cellName==jo[q].cellName){
								var cell=td;
								var type=jo[q].type;
								var code=jo[q].code;
								datas=jo[q].datas;
		                		var key=jo[q].value;
		            			td.classList.add('jexcel_dropdown');
		            			if(editable){
		            				var v = [];
		                			var combo = [];
		                            var source = datas.split(";");
		                
		                            for (var k = 0; k < source.length; k++) {
		                                if (typeof(source[k]) == 'object') {
		                                    combo[source[k].id] = source[k].name;
		                                } else {
		                                    combo[source[k]] = source[k];
		                                }
		                            }
		                			var keys = ('' + key).split(';');
		                            for (var k = 0; k < keys.length; k++) {
		                                if (combo[keys[k]]) {
		                                    v.push(combo[keys[k]]);
		                                }
		                            }
		                            cell.innerHTML=(v.length > 0) ? v.join('; ') : '';
		                            var value = key;
		                            var data = [];
		                            for (var k = 0; k < source.length; k++) {
		                                data.push(source[k]);
		                            }
		                            var info = cell.getBoundingClientRect();
		                            var editor = document.createElement('div');
		                            editor.style.width = (info.width) + 'px';
		                            //editor.style.height = (info.height - 2) + 'px';
		                            //editor.style.minHeight = (info.height - 2) + 'px';
		                            cell.classList.add('editor');
		                            cell.innerHTML = '';
		                            cell.appendChild(editor);
		                            //每读取一个select就添加一个
		                            var t=[];
		                        	t[0]=cellName;
		                        	t[1]=value;
		                        	t[2]=datas;
		                        	t[3]=type;
		                        	t[4]=code;
		                        	table.selects[table.selects.length]=t;
		                            var wrap=false;
		                            /* if(type=="7"){
		                            	wrap=true;
		                            } */
		                            var options = {
		                                data: data,
		                                wrap:wrap,
		                                multiple: false,
		                                autocomplete: false,
		                                opened:false,
		                                value: value,
		                                width:'100%',
		                                height:editor.style.minHeight,
		                                position: false,
		                                onopen:function(){
		                                	var selectRows=table.getSelectedRows();
			    							var selectCols=table.getSelectedColumns();
			    							td=table.tbody.children[parseInt(selectRows[0].getAttribute("data-y"))].children[selectCols[0]+1];
			                    			cellName = jexcel.getColumnNameFromId([selectCols[0],parseInt(selectRows[0].getAttribute("data-y"))]);
					                		cell=td;
					                		var a;
		                                	for(a=0;a<table.selects.length;a++){
		                                    	if(table.selects[a][0]==cellName){
		                                    		type=table.selects[a][3];
		                                    		code=table.selects[a][4];
		                                    		break;
		                                    	}
		                                	}
		                                },
		                                onchange:function(){
		                                	
		                                },
		                                onclose:function() {
		                                	//监听下拉框的改变
		                                	
		                                	var dropdownValue=cell.children[0].dropdown.close(true);
		                                	//select下拉之后，改变其value值，其余不变
		                                	var a;
		                                	for(a=0;a<table.selects.length;a++){
		                                    	if(table.selects[a][0]==cellName){
		                                    		table.selects[a][1]=dropdownValue;
		                                    		break;
		                                    	}
		                                	}
		                                }
		                            };
		                            jSuites.dropdown(editor, options);
		            			}
		            			else{
		            				table.setValue(cellName,key);
		            			}
		            			
							}
						}
					}
				}
				else{
					td.setAttribute('class','');
				}
				if(null!=detail[i].style){
					td.setAttribute('style',detail[i].style);
				}
				else{
					td.setAttribute('style','');
				}
				if(null!=detail[i].datamerged&&detail[i].datamerged!=""){
					table.setMerge(cellName,parseInt(detail[i].colspan),parseInt(detail[i].rowspan));
				}
			}
			//初始化校验规则
			if(null!=template.rules&&"null"!=template.rules){
				var jo= jQuery.parseJSON(template.rules);
				for(var q=0;q<jo.length;q++){
					var data=new Array();
					data.push(jo[q].cellName);
					data.push(jo[q].min);
					data.push(jo[q].normal);
					data.push(jo[q].max);
					table.rules.push(data);
				}
			}
		},"json");
	}
//获取模板所有数据
function get(){
	cells=[];
	var data=table.getData();//表格上显示的数据或公式
	var i,j;
	for(i=0;i<data.length;i++){
		var tr=table.tbody.children[i];
		for(j=1;j<=data[i].length;j++){
			var td=tr.children[j];
			var tds=[];
			var cellName=jexcel.getColumnNameFromId([j-1,i]);
			tds.push(cellName);
			var x=j-1;
			tds.push(x);
			var y=i;
			tds.push(y);
			var classes=td.getAttribute('class')==null?'':td.getAttribute('class');
			//checkbox格式的单元格与时间、下拉框格式有所不同，
			//不能实时监听改变，所以在最终提交之前统计checkbox
			if(classes.indexOf('checkbox')!=-1){
				var s=[];
				s[0]=cellName;
				s[1]=$("#checkbox"+cellName).is(':checked')+'';
				table.checkboxs.push(s);
			}
			tds.push(classes);
			var style=td.getAttribute('style');
			tds.push(style);
			var colspan=td.getAttribute('colspan')==null?'':td.getAttribute('colspan');
			tds.push(colspan);
			var rowspan=td.getAttribute('rowspan')==null?'':td.getAttribute('rowspan');
			tds.push(rowspan);
			//这是单元格合并的属性
			var merged=td.getAttribute('data-merged')==null?'':td.getAttribute('data-merged');
			tds.push(merged);
			var innerHTML=td.innerHTML;
			tds.push(innerHTML);
			var clientWidth=table.thead.children[0].children[j].clientWidth;
			tds.push(clientWidth+2);
			var clientHeight=tr.clientHeight;
			tds.push(clientHeight);
			//formula是单元格为编辑状态时的值，
			//innerHTML是单元格未编辑状态时的值
			//一般情况下2个值都相等，
			//但在有公式的时候，formula存公式，innerHTML存数值
			var formula=table.options.data[i][j-1];
			if(formula==''){
				formula=innerHTML;
			}
			tds.push(formula);
			cells.push(tds);
		}
	}
	rules=table.rules;
}


</script>
</html>